//
//  MainPageViewController.m
//  PregnancyAPP
//
//  Created by APPYING on 14-2-11.
//  Copyright (c) 2014年 APPYING. All rights reserved.
//

#import "MainPageViewController.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import <CommonCrypto/CommonDigest.h>
#import "UIImage+Resize.h"
#import "ShowAdvertisement.h"

@interface MainPageViewController ()

@end

@implementation MainPageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize
{
    UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return reSizeImage;
}

- (void)viewWillAppear:(BOOL)animated {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor clearColor];
    
    mainView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"ImgMainApp"] croppedImage:CGRectMake(0, 0, 2 * Kwidth, 2 * Kheight)]];
    mainView.frame = CGRectMake(0, 0, Kwidth, Kheight);
    [mainView setClipsToBounds:YES];
    mainView.contentMode = UIViewContentModeScaleAspectFit;
    mainView.userInteractionEnabled = YES;
    [self.view addSubview:mainView];
    
    UIButton *btCalculate = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btCalculate.frame = CGRectMake(55, 380, 210, 50);
    [btCalculate setBackgroundImage:[UIImage imageNamed:@"ImgCalculateButton"] forState:UIControlStateNormal];
    [btCalculate addTarget:self action:@selector(btClick:) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:btCalculate];
    
    
    // 选择框
    uiPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(8, 174, Kwidth - 16, 16)];
    uiPickerView.backgroundColor = [UIColor clearColor];
    uiPickerView.showsSelectionIndicator=YES;
    uiPickerView.dataSource = self;
    uiPickerView.delegate = self;
    [self.view addSubview:uiPickerView];
    _YearList = [[NSArray alloc] initWithObjects:@"2013", @"2014", @"2015", nil];
    _MonthList = [[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", @"11", @"12", nil];
    _DayList = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", @"31", nil];
    
    
    [self autoNextPage];
}

#pragma mark ---------------------------------------------------

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        pickerLabel.textColor = [UIColor whiteColor];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:20]];
    }
    
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

// pickerView 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 4;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 55;
}

// pickerView 每列个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return [_YearList count];
    } else if (component == 1) {
        return [_MonthList count];
    } else if (component == 2) {
        return [_DayList count];
    } else {
        return 0;
    }
}

// 每列宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) {
        return 108;
    } else if (component == 1) {
        return 96;
    } else if (component == 2) {
        return 65;
    } else {
        return 300;
    }
}

// 返回选中的行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([self returnTheTimeIsFrontCurrent] < 0) {
        [pickerView selectRow:currentYear - 2013 inComponent:0 animated:YES];
        [pickerView selectRow:currentMonth - 1 inComponent:1 animated:YES];
        [pickerView selectRow:currentDay - 1 inComponent:2 animated:YES];
    }
    
    if ([self returnTheTimeIsAfterThirdDaysAgo] > 0) {
        [pickerView selectRow:thirdDaysAgoYear - 2013 inComponent:0 animated:YES];
        [pickerView selectRow:thirdDaysAgoMonth - 1 inComponent:1 animated:YES];
        [pickerView selectRow:thirdDaysAgoDay - 1 inComponent:2 animated:YES];
    }
    
    if (component == 1) {
        [_DayList removeAllObjects];
        if (row % 2 == 0) {
            _DayList = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", @"31", nil];
        }
        if (row % 2 == 1) {
            _DayList = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", nil];
        }
        if (row == 1) {
            _DayList = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28", nil];
        }
        if (row == 11 || row == 7 || row == 9) {
            _DayList = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", @"31", nil];
        }
        if (row == 8 || row == 10) {
            _DayList = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", nil];
        }
        [pickerView reloadComponent:2];
    }
}

//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return [_YearList objectAtIndex:row];
    } else if(component == 1) {
        return [_MonthList objectAtIndex:row];
    } else {
        return [_DayList objectAtIndex:row];
    }
}

// 返回当前用户的输入时间是否大于当前时间
- (int)returnTheTimeIsFrontCurrent {
    NSDate *currentInputDate = [self returnCurrentInputDate];
    NSDate *nowDate = [self returnCurrentDate];
    
    return [self compareDate:currentInputDate withDate:nowDate];
}

// 返回当前用户的输入时间是否四十天之前
- (int)returnTheTimeIsAfterThirdDaysAgo {
    NSDate *currentInputDate = [self returnCurrentInputDate];
    NSDate *nowDate = [self returnCurrentDate];
    NSDate *thirdAgoDate = [[NSDate alloc] initWithTimeInterval:-60 * 60 * 24 * 280 sinceDate:nowDate];
    
    return [self compareDate:currentInputDate withDate:thirdAgoDate];
}

// 用户输入时间和比较对象时间的时间前后
-(int)compareDate:(NSDate*)currentInputDate withDate:(NSDate*)compareDate {
    int ci;
    NSComparisonResult result = [currentInputDate compare:compareDate];
    switch (result)
    {
            //compareDate比currentInputDate大
        case NSOrderedAscending: ci=1; break;
            //compareDate比currentInputDate小
        case NSOrderedDescending: ci=-1; break;
            //compareDate=currentInputDate
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", currentInputDate, compareDate); break;
    }
    return ci;
}

// 当前用户输入时间
- (NSDate *)returnCurrentInputDate {
    int inputYear = (int)[uiPickerView selectedRowInComponent:0] + 2013;
    int inputMonth = (int)[uiPickerView selectedRowInComponent:1] + 1;
    int inputDay = (int)[uiPickerView selectedRowInComponent:2] + 1;
    NSString *inputDateString = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", inputYear, inputMonth, inputDay, 0, 0, 0];
    return [self dateFromString:inputDateString];
}

// 当前系统时间
- (NSDate *)returnCurrentDate {
    if (currentYear == 0) {
        [self getCurrentTimeYearMonthDay];
    }
    NSString *inputDateString = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", currentYear, currentMonth, currentDay, 0, 0, 0];
    return [self dateFromString:inputDateString];
}

// 获取当然时间的年月日和40周之前的年月日
- (void)getCurrentTimeYearMonthDay {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    NSDateComponents *comps  = [calendar components:unitFlags fromDate:[NSDate date]];
    
    
    currentYear = [comps year];
    currentMonth = [comps month];
    currentDay = [comps day];
    
    NSDate *thirdAgoDate = [[NSDate alloc] initWithTimeInterval:-60 * 60 * 24 * 280 sinceDate:[self returnCurrentDate]];
    comps  = [calendar components:unitFlags fromDate:thirdAgoDate];
    thirdDaysAgoYear = [comps year];
    thirdDaysAgoMonth = [comps month];
    thirdDaysAgoDay = [comps day];
}

#pragma mark ---------------------------------------------------
//输入的日期字符串形如：@"1992-05-21"
- (NSDate *)dateFromString:(NSString *)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
     return [dateFormatter dateFromString:dateString];
}

#pragma mark click
- (void)btClick:(UIButton *)button {
//    NSString *dateString = nil;
//    int year = pickerView
//    NSDate *selectTime = [self dateFromString:dateString]; // 获取被选中的时间
    NSDate *selectTime = [self returnCurrentInputDate];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:selectTime];
    NSInteger day = [components day];
    NSInteger month= [components month];
    NSInteger year= [components year];
    
    //怀孕日期计算
    NSTimeInterval secondsInterval= [[NSDate date] timeIntervalSinceDate:selectTime];
    pregnancyDay = secondsInterval/(60*60*24);
    //对孕妇输入的时间进行判断
    if((int)pregnancyDay/7 > 40) {
        UIAlertView *alterError = [[UIAlertView alloc] initWithTitle:@"您的预产期已超过" message:@"请重新输入！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alterError show];
        return;
    } else if((int)pregnancyDay/7 < 0) {
        UIAlertView *alterError = [[UIAlertView alloc] initWithTitle:@"亲，先找男朋友的啦" message:@"请重新输入！" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alterError show];
        return;
    }
    
    calculateViewController = [[CalculateViewController alloc] init];
    calculateViewController.delegate = self;
    calculateViewController.day = day;
    calculateViewController.month = month;
    calculateViewController.year = year;
    calculateViewController.pregnancyData = selectTime;
    [self.navigationController pushViewController: calculateViewController animated:NO];
}

// 读取现在文件存储里面的时间对应的数字
- (void)getCurrentFileTime {
    NSDictionary *dic2 = [self havePlistFile];
    if(dic2 != nil && [dic2 objectForKey:@"day"] != nil) {
        
        NSString *dayRead = [dic2 objectForKey:@"day"];
        NSString *monthRead = [dic2 objectForKey:@"month"];
        NSString *yearRead = [dic2 objectForKey:@"year"] ;
        
        dayReadInt = [dayRead intValue];
        monthReadInt = [monthRead intValue];
        yearReadInt = [yearRead intValue];
    }
}

//判断是否有存储文件
- (NSDictionary *)havePlistFile {
    //判断是否已经有数据在plist文件中，如果有，则转到下一个页面
    //读取plist文件，首先需要把plist文件读取到字典中
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [path objectAtIndex:0];
    NSString *plistPath = [filePath stringByAppendingPathComponent:@"test.plist"];
    NSDictionary *dic2 = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    return dic2;
}

//如果有存储文件，则自动进入下一个页面
- (void)autoNextPage {
    NSDictionary *dic2 = [self havePlistFile];
    if(dic2 != nil && [dic2 objectForKey:@"day"] != nil) {
        
        NSString *dayRead = [dic2 objectForKey:@"day"];
        NSString *monthRead = [dic2 objectForKey:@"month"];
        NSString *yearRead = [dic2 objectForKey:@"year"] ;
        
        dayReadInt = [dayRead intValue];
        monthReadInt = [monthRead intValue];
        yearReadInt = [yearRead intValue];
        
        NSString *dateString = [NSString stringWithFormat:@"%@-%@-%@ 0:0:0", yearRead, monthRead, dayRead];
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat: @"yyyy-MM-dd"];
        NSDate *destDate= [self dateFromString: dateString];
//
//        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:destDate];
//        NSInteger day = [components day];
//        NSInteger month= [components month];
//        NSInteger year= [components year];
        
        NSInteger day = [dayRead intValue];
        NSInteger month= [monthRead intValue];
        NSInteger year= [yearRead intValue];
        
        calculateViewController = [[CalculateViewController alloc] init];
        calculateViewController.delegate = self;
        calculateViewController.day = day;
        calculateViewController.month = month;
        calculateViewController.year = year;
        calculateViewController.pregnancyData = destDate;
        [self.navigationController pushViewController: calculateViewController animated:YES];
    } else {// 本页面数据刷新
        
        [self getCurrentTimeYearMonthDay];

        [uiPickerView selectRow:currentYear - 2013 inComponent:0 animated:YES];
        [uiPickerView selectRow:currentMonth - 1 inComponent:1 animated:YES];
        [uiPickerView selectRow:currentDay - 1 inComponent:2 animated:YES];
        
        // 添加广告SDK
        ShowAdvertisement *test = [[ShowAdvertisement alloc] init];
        test.target = test;
        UIView *adView = [test showAdvertisement:@"5412ba8de4b080380a486a57"];
        [self.navigationController.view addSubview:adView];

    }
}


- (CGSize)contentCellHeightWithText:(NSString*)text andFont:(UIFont *)font {
        //设置字体
        CGSize size = CGSizeMake(300, 20000.0f);//注：这个宽：300 是你要显示的宽度既固定的宽度，高度可以依照自己的需求而定
        if (version < 6)//IOS 7.0 以上
        {
            NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
            size =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
        }
        else
        {
//            size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];//ios7以上已经摒弃的这个方法
        }
        return size;
}

//判断联网标志
- (BOOL)connectedToNetwork {
    
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    
    struct sockaddr_storage zeroAddress;
    
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable&&!needsConnection) ? YES : NO;
}

#pragma mark CalculateViewControllerDelegate
// 从下一个页面返回时候显示已经定好的时间
-(void)DoSomething {
    self.navigationController.navigationBarHidden = YES;
    
    [self getCurrentFileTime];
    
    [uiPickerView selectRow:yearReadInt - 2013 inComponent:0 animated:YES];
    [uiPickerView selectRow:monthReadInt - 1 inComponent:1 animated:YES];
    [uiPickerView selectRow:dayReadInt - 1 inComponent:2 animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end